package com.sockrt;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/** SocketClint01
 * @author 陈志安
 * @version 1.0
 * 客户端
 */
public class SocketClint02 {
    public static void main(String[] args) throws IOException {
        //思路
        //1.连接服务端(ip,端口)
        Socket socket=new Socket(InetAddress.getLocalHost(),9999);
        //2.连接上后,生成socket
        System.out.println("客户端"+socket.getClass());
        OutputStream outputStream=socket.getOutputStream();
        BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello i am client2");
        bufferedWriter.newLine();//插入换行符,表示写入的内容结束  注意:要求对方使用readline()
        bufferedWriter.flush();//手动刷新,否则写入不到指定的文件
//        outputStream.write("hello my lover".getBytes());
        socket.shutdownOutput();

        //读消息
        InputStream inputStream=socket.getInputStream();
//        int readline=0;
//        byte[]buf=new byte[100];
//        while((readline=inputStream.read(buf))!=-1){
//            System.out.println(new String(buf,0,readline));
//        }
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
        String readline=bufferedReader.readLine();
        System.out.println("客户端读取"+readline);
        bufferedReader.close();
        outputStream.close();
        socket.close();
    }
}
